package 多线程.ThreadLocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class ThreadLocalUseDemo2 {

    //public static ThreadLocalUseDemo2.Number number = new ThreadLocalUseDemo2.Number(0);

    /**
     * 初始化 num值。使用时，先通过get方法获取。
     */
    public static ThreadLocal<ThreadLocalUseDemo2.Number> threadLocalValue = new ThreadLocal<ThreadLocalUseDemo2.Number>() {
        @Override
        protected Number initialValue() {
            return new Number(0);
        }
    };

    /**
     * 数据类
     */
    private static class Number {
        public Number(int num) {
            this.num = num;
        }

        private int num;

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        @Override
        public String toString() {
            return "Number [num=" + num + "]";
        }
    }

    /**
     * 线程类：
     */
    public static class ThreadDemo2 extends Thread {

        @Override
        public void run() {
            // 如果没有初始化，注意NPE。
            // static修饰的 number时，注释掉这句
            Number number = threadLocalValue.get();

            //每个线程计数加随机数
            Random r = new Random();
            number.setNum(number.getNum() + r.nextInt(100));
            //将其存储到ThreadLocal中
            threadLocalValue.set(number);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //打印保存的随机值
            System.out.println(Thread.currentThread().getName() + " -》 " + threadLocalValue.get().getNum());
            threadLocalValue.remove();
            System.out.println(Thread.currentThread().getName() + " remove方法之后 -》 " + threadLocalValue.get().getNum());
        }

    }

    public static void main(String[] args) {
        // 启动5个线程
        for (int i = 0; i < 5; i++) {
            new ThreadDemo2().start();
        }
    }
}
